package logic

import (
	"context"
	"fmt"
	"person/models/cathe"
	"person/models/mysql"

	"person/personrpc/internal/svc"
	"person/personrpc/personrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type LoginLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LoginLogic {
	return &LoginLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *LoginLogic) Login(in *personrpc.LoginRequest) (*personrpc.LoginResponse, error) {
	// todo: add your logic here and delete this line
	var findUser mysql.User
	mysql.DB.Debug().Where("mobile = ?", in.Mobile).Find(&findUser)
	if findUser.ID == 0 {
		return nil, fmt.Errorf("当前账号未注册，请前去注册")
	}

	if in.Password == "" {
		sms := cathe.Rdb.Get(l.ctx, "sendSms"+"login"+in.Mobile)
		if sms.Val() != in.SmsCode {
			return nil, fmt.Errorf("短信验证码错误")
		}
	} else {
		if findUser.Password != in.Password {
			return nil, fmt.Errorf("密码错误，请重新输入")
		}
	}

	return &personrpc.LoginResponse{
		Id: int64(findUser.ID),
	}, nil
}
